//index.js
//获取应用实例
var app = getApp(); 
//console.log(app.globalData);
Page({
  data: {
    userInfo: {},
    imageList:[],
    imageKeys:[],
    topicType:2,
    groupData:{},
    topicData:{},
    videoSrc:'',
    videoKey:'',
    setDate:0,
    time:'',
    showlables:0,
    password:'',
    topic_id:0,
    idays:0,
    chooseVideoText:'选择视频',
    status:0,
    statusArray: ['公开', '仅自己可看'],
    content:'',
    remainTypeArray: ['日期', '周'],
    weekList: [],
    weekListStr: [],
    remainType: 3,
    time: '',
    startdate: '',
    enddate: '',
    cateArray: ['未开始', '进行中', '己完成'],
    cate_id: 0,
    signIn:1,
    dateArray:['1天','1周'],
    averageDayIndex:0,
    pidArray: [],
    pidindex:'',
    signCount: 1,
    averageDay: 1,
    countArray: [1, 2, 3, 4, 5, 6, 7],
    canEditSign:1,

  },
  bindStatusChange: function (e) {
    var v = Number(e.detail.value);
    this.setData({ status: v });
  },
  bindlables:function(e){
    var value = e.detail.value;
    var lables = this.data.groupData.lables;
    var lables2=[];
    for (var i in lables){
      var title = lables[i].title;
      if (title.indexOf(value) === 0 || value==''){
        lables2.push(title);
      }
    }
    if (lables2.length == 0 || lables2[0] == value){
      this.setData({ lables: lables2, showlables:0});
    }else{
      this.setData({ lables: lables2, showlables: 1 });
    }
   // this.setData({ showlables: 1 });
   // console.log(lables2);
  },

  
  datedifference:function() {    //sDate1和sDate2是2006-12-  
    var sDate1=this.data.startdate;
    var sDate2=this.data.enddate;
    var idays= app.DateDiff(sDate1, sDate2);
    this.setData({ idays: idays });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //console.log(options);
    //options.topic_id = 83556;
    this.setData({ startYear: app.date(), startdate: app.date() })
    this.setData({ enddate: app.date(7) })
    this.setData({ window: app.globalData.window, pid: options.pid ? options.pid : 0, pid2: options.pid2 ? options.pid2 : 0, topic_id: options.topic_id })
    if (this.data.pid>0){
      this.getGroup();
      this.setData({ topicType:2});

    }
    if (this.data.pid2 ){
      this.getTopic();
      this.setData({ topicType: 1 });
      wx.setNavigationBarTitle({
        title: '打卡'
      });
    }
    //console.log(this.data);
    if (this.data.topic_id>0){
      this.getTopic();
      wx.setNavigationBarTitle({
        title: '修改'
      });
    }else{
      this.getPidArray();
    }
    
    //this.getTopicList();
  },

  getPidArray: function () {
    var that = this;
    app.api("group/get", {
      order: 'orderBy',
      status: 1,
      type: 'todolist',
    }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
        return;
      }
      if (res.data.list.length > 0) {
        var pidArray = [];
        var pidindex='';
        for (var i in res.data.list) {
          if (res.data.list[i].id == that.data.pid){
            pidindex = i;
          }
          pidArray.push(res.data.list[i].value);
        }
        that.setData({
          pidArray: pidArray, groupList: res.data.list, pidindex: pidindex
        });
      }
    })
  },
  switch2Change: function (e) {
    var name = e.currentTarget.dataset.type;
    if (name == "setDate") {
      console.log(e.detail.value);
      this.setData({ setDate: e.detail.value });
    } else if (name == "signIn") {
      this.setData({ signIn: e.detail.value });
    }
  },

  getTopic: function () {
    console.log("getTopic");
    var that = this;
    var pid = this.data.pid2;
    var topic_id = this.data.topic_id;
    var id = topic_id ? topic_id : pid;
    app.api("topic/detail", {
      id: id,
    }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
        return;
      }
      that.getPidArray();
      that.setData({ topicData: res.data, pid: res.data.pid, groupData: res.data.group});
      that.setData({
        signIn: res.data.content_data.signIn
      })
      if (topic_id>0){
        console.log(res.data.group);
        that.setData({
          imageList: res.data.pics,
          imageKeys: res.data.imageKeys,
          videoSrc: res.data.video_url,
          videoKey: res.data.videoKey,
          content: res.data.title,
          cate_id: res.data.cate_id,
          pid :res.data.pid,
          pid2: res.data.pid2,
          status: Number(res.data.status2)-1,
          password: res.data.password,
          setDate: res.data.content_data.setDate,
          enddate: res.data.content_data.enddate,
          startdate: res.data.content_data.startdate,
          signIn: res.data.content_data.signIn,
          signCount: res.data.content_data.signCount,
          averageDay: res.data.content_data.averageDay,
          main_title: res.data.content ? res.data.content.main_title : "",
         });

         if(res.data.pid2>0){
           that.setData({ topicType: 1});
         }
         if (res.data.join_count>0){
           that.setData({ canEditSign:0});
         }
         if (res.data.content && res.data.content.length>0){
           var contentData =  JSON.parse(res.data.content);
           that.setData(contentData)
         }
      }
    })
  },


  //
  getGroup: function () {
    var that = this;
    var pid = this.data.pid;
    app.api("group/find", {
      id: pid
    }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
        return;
      }
      that.setData({ groupData: res.data });
      //主题只能参与一次，那么直接发动态了
      if (res.data.content.joinLimit == 1 && res.data.joined.code == 0 && that.data.pid2==0){
        var topicData = res.data.joined.data;
        that.setData({ topicData: topicData, pid2: topicData.id, topicType: 1});
        wx.setNavigationBarTitle({
          title: '添加'
        });
      }else{
        wx.setNavigationBarTitle({
          title: res.data.content.issuePageTitle
        });
      }
    })
  },
  delImgVideo:function(){
    this.setData({
      videoSrc: '',
      videoKey: '',
    })
  },
  choose: function () {
    var that = this;
    if (this.data.videoSrc.length > 0 && this.data.imageKeys.length == 0) {
      that.chooseImage();
      return;
    }
    if (this.data.imageKeys.length > 1) {
      that.chooseImage();
      return;
    }

    wx.showActionSheet({
      itemList: ['上传图片', '上传视频'],
      success: function (res) {
        if (res.tapIndex == 0) {
          that.chooseImage();
        } else if (res.tapIndex == 1) {
          that.chooseVideo();
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  chooseVideo: function () {
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function (res) {
        var filePath = res.tempFilePath;
        that.setData({ chooseVideoText: '上传中...' });
        app.upload(filePath, (res) => {
          console.log(res);
          that.setData({ chooseVideoText: '选择视频' });
          that.setData({
            videoSrc: res.imageURL,
            videoKey:res.key,
          })
        })

      }
    })
  },

  chooseImage:function(){
    var that = this
    var imageList = this.data.imageList;
    var imageKeys = this.data.imageKeys;
    // if (this.data.topicType==2){
    //   var max = 3 - this.data.imageList.length;
    // }else{
    //   var max =1;
    // }
    var max = 3;
    //上传了视频那只能上传一张图片 
    if (this.data.videoSrc.length > 0){
      var max = 1;
    }
    wx.chooseImage({
      sizeType: 'compressed',
      count: max,
      success: function (res) {
        var newImages = res.tempFilePaths;
        for (var i in newImages){
          var filePath = newImages[i];
          app.upload(filePath, (res) => {
            imageList = imageList.concat(res.imageURL);
            imageKeys = imageKeys.concat(res.key) ;
            that.setData({ imageList: imageList, imageKeys: imageKeys});
          })
        }
      }
    })
  },
  delImg:function(e){
    var id = e.currentTarget.dataset.id;
    var imageList = this.data.imageList;
    var imageKeys = this.data.imageKeys;
    imageList.splice(id, 1);
    imageKeys.splice(id, 1);
    this.setData({ imageList: imageList, imageKeys: imageKeys});
  },
  //浏览图片
  previewImage: function (e) {
    var current = e.target.dataset.src
    wx.previewImage({
      current: current,
      urls: this.data.imageList
    })
  },
  //发布活动 
  formSubmit: function (e) {
    var formId = e.detail.formId;
    var user_info = app.globalData.userInfo;
    var postData = e.detail.value;
    if (this.data.loading == 1) {
      return;
    }
    //创建心愿单
   if(!this.data.pid2){
     if (postData.title == "") {
       app.alert('请先输入计划标题');
       return false;
     }
     if (!this.data.pid) {
       app.alert('请先输入计划类型');
       return false;
     }
     if (postData.desc == "") {
       app.alert('请先输入计划内容');
       return false;
     }
   }else{
      
     if (this.data.groupData.content.mainTitlePlaceholder && postData.main_title== "") {
       app.alert(this.data.groupData.content.mainTitlePlaceholder);
       return false;
     }
     if (postData.title == "" && this.data.imageKeys.length == 0 && this.data.videoKey.length == 0) {
       app.alert('请先添加视频/文字/图片,其中一种内容');
       return false;
     }
   }
    
    // if (this.data.videoSrc.length > 0 && this.data.imageKeys.length == 0) {
    //   app.alert('添加视频封面图片');
    //   return false;
    // }
    //添加动态
    // if (this.data.pid2) {
     
    // }
    // if (this.data.cate_id == 2 && this.data.imageKeys.length == 0) {
    //   app.alert('请上传一张封面图');
    //   return false;
    // }
    var groupData = this.data.groupData;
    console.log(this.data);
    if (this.data.pid2>0 && groupData && groupData.content && groupData.content.mainTitlePlaceholder && !postData.main_title){
      app.alert(groupData.content.mainTitlePlaceholder);
      return false;
    }


    this.setData({ 'loading': 1 });
    this.setData({ 'disabled': 1 });
    var _this = this;
    var title = postData.title;
    
    var signIn = 0;
    if (this.data.pid2 > 0 && this.data.signIn){
      signIn=1;
    }
    var contentData = {
      signIn: this.data.signIn,
      noti: this.data.noti,
      setDate: this.data.setDate,
    };
    //打卡类型的计划
    if (this.data.signIn) {
      contentData.signCount = this.data.signCount;
      contentData.averageDay = this.data.averageDay;
      contentData.money = this.data.money;
    }
   if (postData.main_title){
     contentData.main_title = postData.main_title;
    }

   if (this.data.setDate){
     contentData.startdate = this.data.startdate;
     contentData.enddate = this.data.enddate;
   }

 
    //提交回答
    app.api("topic/add", {
      title: title,
      formId: formId,
      signIn:signIn,
      desc: postData.desc,
      status: Number(this.data.status)+1,
      pics: this.data.imageKeys.join(","),
      type:'todolist',
      pid:this.data.pid,
      id:this.data.topic_id,
      pid2:this.data.pid2,
      password: postData.password,
      video_url: this.data.videoKey,
      content: JSON.stringify(contentData),
     // cate_id: this.data.cate_id,
      method: 'POST',
    }, function (res) {
      _this.setData({ 'loading': 0 });
      _this.setData({ 'disabled': 0 });
      var title = "";
      if (res.code == 200) {
        // wx.showToast({
        //   title: '发布成功',
        //   icon: 'success',
        //   duration: 2000
        // });
        
        var topic_id = res.data.id;
        if (!_this.data.signIn){//心愿单
          _this.join_topic(topic_id);
        }else{
          _this.suc();
        }
        // 
      //  
       // _this.navigateBack();
      } else {
        app.alert(res.msg);
      }
    })
  },

  join_topic: function (topic_id) {
    var that = this;
    if (that.data.payloading == 1) {
      return false;
    }
    that.data.payloading = 1;
    app.api("topicjoin/join", {
      topic_id: topic_id,
      status:0,
    }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
        that.data.payloading = 0;
        that.setData({ 'loading': 0 });
        that.setData({ 'disabled': 0 });
        return false;
      }
      that.suc();
    })
  },

  pay: function (topic_id) {
    var that = this;
    if (that.data.payloading == 1) {
      return false;
    }
    that.data.payloading = 1;
    app.api("pay/topic_join", {
      topic_id: topic_id
    }, function (res) {
      if (res.code != 200) {
        app.alert(res.msg);
        that.data.payloading = 0;
        that.setData({ 'loading': 0 });
        that.setData({ 'disabled': 0 });
        return false;
      }
      var order_sn = res.data.order_sn;
      app.api("pay/topay", {
        order_sn: order_sn
      }, function (res) {
        if (res.code != 200) {
          app.alert(res.msg);
          that.data.payloading = 0;
          that.setData({ 'loading': 0 });
          that.setData({ 'disabled': 0 });
          return false;
        }
        if (res.data.over == 1) {
          that.suc();
          return;
        }
        var params = res.data;
        //params.total_fee = 0.1;
        params.success = function (res) {
          that.suc();
        }
        params.fail = function (res) {
          console.log(res);
          if (res.errMsg == 'requestPayment:fail cancel') {
            //  wx.navigateBack({
            //    delta: 1
            //  })
            that.setData({ 'loading': 0 });
            that.setData({ 'disabled': 0 });
            return false;
          }
          app.alert(res.errMsg);
        }
        console.log(params);
        wx.requestPayment(params)

      })
    })
  },

  suc: function () {
    var _this = this;
    wx.showToast({
      title: '发布成功',
      icon: 'success',
      duration: 2000
    });
    app.setPageData("index/index", { reload: 1 });
    app.setPageData("index/index", { reload2: 1 });
    app.setPageData("group/index", { reload: 1 });
    app.setPageData("user/timeline", { reload: 1 });
    app.setPageData("user/timeline", { reload2: 1 });
    _this.navigateBack();
  },
//返回 
  navigateBack: function (e){
   wx.navigateBack({
      delta: 1
    })
  },
  bindTimeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },
  bindRemainTypeChange: function (e) {
    //console.log(e);
    var v = Number(e.detail.value);
    this.setData({ remainType: v });
    if (v == 1) {
      this.setData({ orderListActive: 1 });
    }
  },
 

  bodyclick() {
    console.log('bodyclick');
    if (this.data.orderListActive == 1) {
      this.setData({ orderListActive: 0 });
    }
  },
  showWeek: function () {
    this.setData({ orderListActive: 1 });
  },
  chooseWeek: function (e) {
    var index = app.in_array(e.currentTarget.dataset.key, this.data.weekList)
    if (index === false) {
      this.data.weekList.push(e.currentTarget.dataset.key);
      this.data.weekListStr.push(e.currentTarget.dataset.text);
    } else {
      this.data.weekListStr.splice(index, 1);
      this.data.weekList.splice(index, 1);
    }
    this.setData({
      weekList: this.data.weekList,
      weekListStr: this.data.weekListStr
    });
    //console.log(this.data.weekListStr);
  },
  bindCateChange: function (e) {
    var v = Number(e.detail.value);
    this.setData({ cate_id: v });
  },
  selectmaintitle:function(e){
   var text =  e.currentTarget.dataset.text;
   this.setData({ main_title: text, showlables:0});
  },
  showlables:function(){
    var lables = this.data.groupData.lables;
    var lables2 = [];
    for (var i in lables) {
      var title = lables[i].title;
      lables2.push(title);
    }
    
    this.setData({ lables: lables2,  showlables: 1 });
  },
  hidelables: function () {
    this.setData({ showlables: 0 });
  },
  //设置时间
  bindDateChange: function (e) {
    var v = e.detail.value;
    var name = e.currentTarget.dataset.name;
    if (name == "enddate") {
      this.setData({ enddate: v });
    } else {
      this.setData({ startdate: v });
    }
    this.datedifference();

  },
  bindCountChange: function (e) {
    var v = Number(e.detail.value) + 1;
    var name = e.currentTarget.dataset.type;
    if (name == "averageDay") {
      this.setData({ averageDay: v });
    } else if (name == "signCount") {
      this.setData({ signCount: v });
    }
  },
  bindTypeChange: function (e) {
    this.setData({ pidindex: e.detail.value });
    this.data.pid = this.data.groupList[e.detail.value].id;
    //console.log(this.data.pid);
  },
  aboutmoney: function () {
    // if (!this.data.money || this.data.money<=0){
    //    app.alert("请先设置打卡金，再查看");
    //    return ;
    // }
    var content = "每人加入计划需要支付的金额，完成计划的人可以瓜分总金额";
    wx.showModal({
      title: '嗯，对！钱能使用我自律!',
      content: content,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  bindCateChange: function (e) {
    var v = Number(e.detail.value);
    this.setData({ cate_id: v });
  },
  bindAverageDayChange:function(e){
    var v = Number(e.detail.value);
   if(v==1){
     this.data.averageDay=7;
   }else{
     this.data.averageDay = 1;
   }

    this.setData({ averageDayIndex: v });
  },
  setMoney: function (e) {
    this.data.money = e.detail.value;
    this.setData({ money: e.detail.value });
  },
  onShow:function(e){
    this.datedifference();
  }
 

  
})
